const http = {
	// 接口 baseUrl
	baseUrl: "http://47.94.6.186:3006",
	// 请求方法
	request(config) {
		// 请求拦截
		config = beforeRequest(config);
		// 封装实际请求 url
		config.url = this.baseUrl + config.url;
		return new Promise((resolve, reject) => {
			// uni.request
			uni.request(config)
				.then(res => {
					const response = beforeReponse(res);
					resolve(response);
				}).catch(error => {
					errorHandle(error);
					reject(error);
				})
		})
	},
	get(url, params) {
		return this.request({
			url: url,
			data: params,
			method: "GET"
		})
	},
	post(url, data) {
		return this.request({
			url: url,
			data: data,
			method: "POST"
		})
	},
	put(url, data) {
		return this.request({
			url: url,
			data: data,
			method: "PUT"
		})
	},
	delete(url, data) {
		return this.request({
			url: url,
			data: data,
			method: "DELETE"
		})
	},
}

// 请求拦截
const beforeRequest = (config) => {
	const token = uni.getStorageSync("token");
	const header = {
		'content-type': 'application/json'
	};
	// if (token) {
	// 	//config.header["token"] = token;
    //     // header["token"] = token
    //     config.header.authorization = 'Bearer '+token
	// }
	// 确保config.header存在
    if (!config.header) {
      config.header = {};
    }
    Object.assign(config.header, header)
	return config;
}
// 响应拦截
const beforeReponse = (response) => {
    // console.log(response)
	// 检查token是否过期或无效
	if (response.data && (response.data.code === '10119' || response.data.message === 'token无效')) {
		// 清除本地存储的token和用户信息
		uni.removeStorageSync('token');
		
		// 显示提示信息
		uni.showToast({
			title: '登录已过期，请重新登录',
			icon: 'none'
		});
		
		// 跳转到登录页面
		uni.navigateTo({
			url: '/pages/login/login'
		});
	}
	return response;
}
// 异常处理
const errorHandle = (response) => {
	console.log('异常处理');
}

export default http